package com.foxitcloud.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.foxitcloud.webpdf.WebPDFService;
import com.foxitcloud.webpdf.common.Config;
import com.foxitcloud.webpdf.common.ConfigConstans;
import com.foxitcloud.webpdf.entity.Signature;
import com.foxitcloud.webpdf.parameter.PdfOperationParameter;

@RestController
@Scope("prototype")
@RequestMapping(value = "rest/webpdf")
public class WebpdfController {
	
	@Autowired
	private WebPDFService webPDFService = null;
	
	private static final Logger logger = LoggerFactory.getLogger(WebpdfController.class);
	
	/**
	 * Prepare a document for later analysis. Basically this method would start the processing/conversion of
	 * a PDF document.
	 * 
	 * @param s3Key The location of the document
	 */
	@RequestMapping(value = "/prepare", method = RequestMethod.GET, headers = { "Accept=application/json" })
	public @ResponseBody Map<String, Object> prepare(
			@RequestParam(value = "s3Key", required = true) String s3Key,
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode,
			@RequestParam(value = "psd", required = false, defaultValue = "") String pdfPassword) 
	{
		logger.info(String.format("Prepare a document, s3Key: %s, formMode: %s", s3Key, String.valueOf(formMode)));
		return webPDFService.prepare(s3Key, formMode, pdfPassword);
	}	
	
	//1.获取文档信息数据: (GET)		https://webpdf.foxitcloud.com/asserts/{sessionId}/manifest
	@RequestMapping(value = "/manifest", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getSummaryInfo(HttpServletResponse response,
			@RequestParam(value = "s3Key", required = true) String s3Key,
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode,
			@RequestParam(value = "isCheckPsd", required = false, defaultValue = "false") boolean isCheckPsd,
			@RequestParam(value = "psd", required = false, defaultValue = "") String pdfPassword
			) 
	{
		logger.info(String.format("Get manifest information, s3Key: %s, formMode: %s, isCheckPsd: %s", 
				s3Key, String.valueOf(formMode), isCheckPsd));
		return webPDFService.getSummaryInfo(response,s3Key,formMode, isCheckPsd, pdfPassword);
	}
	
	
	//2.获取annot数据：(GET)	https://webpdf.foxitcloud.com/asserts/{sessionId}/annots	
	@RequestMapping(value = "/annots",method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getAnnotData(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "s3Key", required = true) String s3Key,
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode){
		logger.info(String.format("Get annot information, s3Key: %s, formMode: %s", 
				s3Key, String.valueOf(formMode)));
		return webPDFService.getAnnotData(request,response,s3Key, formMode);
	}


	//3.获取bookmark数据：(GET)		https://webpdf.foxitcloud.com/asserts/{sessionId}/bookmarks	
	@RequestMapping(value = "/bookmarks",method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getBookMarkData(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "s3Key", required = true) String s3Key, 
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode){
		logger.info(String.format("Get bookmarks information, s3Key: %s, formMode: %s", 
				s3Key, String.valueOf(formMode)));
		return webPDFService.getBookMarkData(request,response,s3Key, formMode);
	}
	
	/**
	 * 4.后去表单域控件背景图片：(GET) https://webpdf.foxitcloud.com/asserts/{sessionId}/form/bg/{index}
	 * @param s3Key
	 * @param pageIndex
	 * @param response
	 * @param request
	 * @throws IOException
	 * 
	 */
	@RequestMapping(value = "/form/bg/{index}",method = RequestMethod.GET)
	public void getFormImg(@RequestParam(value = "s3Key", required = true) String s3Key,
			@PathVariable("index") int pageIndex,HttpServletResponse response,
			HttpServletRequest request) throws IOException{
		    logger.info(String.format("Access to form the background image, s3Key: %s, index: %s", 
					s3Key, String.valueOf(pageIndex)));
			webPDFService.getFormImg(s3Key, pageIndex, response);
	}	
	
	/**
	 * 5.获取表单XML数据：(GET)
	 * @param s3Key
	 * @param pageIndex
	 * @param response
	 * @param request
	 * @return
	 * @throws IOException
	 * 
	 * https://webpdf.foxitcloud.com/asserts/{sessionId}/form/xml/{index}
	 */
	@RequestMapping(value = "/form/xml/{index}",method = RequestMethod.GET)
	public void getFormPageXml(@RequestParam(value = "s3Key", required = true) String s3Key,
			@PathVariable("index") String pageIndex,HttpServletResponse response,
			HttpServletRequest request) throws IOException{
			logger.info(String.format("Access to form the xml file, s3Key: %s, index: %s", 
				s3Key, pageIndex));
			webPDFService.getFormPageXml(s3Key, pageIndex, response);
	}	
	

	/**
	 * 6.获取文本数据：(GET)
	 * @param s3Key
	 * @return
	 * 
	 * https://webpdf.foxitcloud.com/asserts/{sessionId}/text/{index}
	 * @throws IOException 
	 */
	@RequestMapping(value = "/text/{index}",method = RequestMethod.GET)
	public Map<String, Object> getPageTextData(
			@RequestParam(value = "s3Key", required = true) String s3Key,
			@PathVariable("index") int pageIndex,
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode,
			HttpServletResponse response,HttpServletRequest request) throws IOException{
		logger.info(String.format("Get text information, s3Key: %s, index: %s", 
				s3Key, pageIndex));
		return webPDFService.getPageTextData(s3Key, pageIndex, formMode, response, request);
	}	

	/**
	 * 7.获取页面背景图片：（GET）https://webpdf.foxitcloud.com/asserts/{sessionId}/image/{index}/{zoom}
	 * @param request
	 * @param response
	 * @param sessionId
	 * @param index
	 * @param form
	 * @param formMode
	 * @param zoom	 
	 */
	@RequestMapping(value = "/image/{index}/{zoom}", method = RequestMethod.GET)
	public void GetPageImg(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "s3Key", required = true) String s3Key,
			@PathVariable("index") int index,
			@RequestParam(value = "form", required = false) boolean isFormAndFormMode,//是表单并且是表单模式
			@RequestParam(value = "formMode", required = false, defaultValue = "false") boolean formMode,
			@PathVariable("zoom") String zoom) {
		logger.info(String.format("Access to page the background image, s3Key: %s, index: %s, formMode: %s", 
				s3Key, String.valueOf(index), String.valueOf(formMode)));
		webPDFService.getImageData(response, request, s3Key, index,
				isFormAndFormMode, formMode, zoom);			
	}
	
	// 8.对PDF文件的操作：（POST） https://webpdf.foxitcloud.com/asserts/{sessionId}/pdfOperation
	@RequestMapping(value = "/pdfOperation", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> pdfOperation(
			@RequestBody PdfOperationParameter pdfOperationParameter
			) 
	{
		logger.info(String.format("Access to page the background image, s3Key: %s", 
				pdfOperationParameter.getS3Key()));
		return webPDFService.pdfOperation(pdfOperationParameter);
	}	

	
	
	@RequestMapping(value = "/signatureList",method = RequestMethod.GET)
	public @ResponseBody String SignatureList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "userId", required = false) String userId) throws Exception {	
		
		logger.info(String.format("Get signatureList, userId: %s", userId));
		List<Signature> sigList = new ArrayList<Signature>();
		JSONObject jsonres = new JSONObject();
		if (sigList != null){
			jsonres.put("success", true);
			jsonres.put("data", (new JSONArray(sigList)).toString());
		}
		else{
			jsonres.put("success", false);
		}		

		jsonres.put("limit", 1);		
		jsonres.put("signcodeUrl","https://forms.vagrant.foxitcloud.com/api/sigcode?csrf=skip&origin=");
		return jsonres.toString();		
	}
	
//	12.获取签名模版图片： https://webpdf.foxitcloud.com/asserts/{sessionId}/signature/{path}
	@RequestMapping(value = "/signature/{path}", method = RequestMethod.GET)
	public void GetSigImg(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("path") String path) throws Exception {		
		logger.info(String.format("Get signature image, id: %s", path));
		webPDFService.getSignatureImgStream(response, path);		
	}
	
//	13.创建签名转换图片接口：（POST）https://webpdf.foxitcloud.com/asserts/{sessionId}/previewImage
	


//
//	/**
//	 * Retrieve the summary information about a document, such as number of pages, etc.
//	 * 
//	 * @param s3Key The location of the document
//	 * @return A full structure of the information. In case of error, the status should be one of:
//	 * DOC_NOT_FOUND, TRY_LATER (just started processing, or is processing, client should try later)
//	 */
//	@RequestMapping(value = "/get-summary-info", method = RequestMethod.GET, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter getSummaryInfo(
//			String s3Key
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//	
//	/**
//	 * Retrieve the DETAIL information about a document, including all page images, and all page text/data/annotation, etc.
//	 * This method would fail if the processing is not completed yet.
//	 * 
//	 * @param s3Key The location of the document
//	 * @return A full structure of the information. In case of error, the status should be one of:
//	 * DOC_NOT_FOUND, TRY_LATER (just started processing, or is processing, client should try later)
//	 */
//	@RequestMapping(value = "/get-detail-inf", method = RequestMethod.GET, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter getDetailInfo(
//			String s3Key
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//	
//	/**
//	 * Retrieve the image of a given page in a document.
//	 * 
//	 * @param s3Key The location of the document
//	 * @param pageNumber The page being requested
//	 * 
//	 * @return A full structure that includes the shared storage location (AWS or local) of the image file
//	 */
//	@RequestMapping(value = "/get-image-for-page", method = RequestMethod.GET, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter getImageForPage(
//			String s3Key,
//			int pageNumber
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//
//	/**
//	 * Retrieve all the textual information (text, annotation, forms fields) of a given page in a document.
//	 * 
//	 * @param s3Key The location of the document
//	 * @param pageNumber The page being requested
//	 * 
//	 */
//	@RequestMapping(value = "/get-info-for-page", method = RequestMethod.GET, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter getInfoForPage(
//			String s3Key,
//			int pageNumber
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//	
//	/**
//	 * Attach/Affix a signature to a document
//	 * 
//	 * @param s3Key The location of the original document
//	 * @signatureLocation A structure holding the page number, x, y coordinates of the signature
//	 * @signature A structure holding the image, font, size, style of the signature
//	 * 
//	 * @return A s3Key for the document with signature generated
//	 */
//	@RequestMapping(value = "/attach-signature", method = RequestMethod.POST, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter attachSignature(
//			String s3Key,
//			String signatureLocation, 	
//			String signature  
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//	
//	/**
//	 * Parse form structure of a fillable form document
//	 * 
//	 * @param s3Key The location of the fillable PDF document
//	 * 
//	 * @return A JSON data structure of ALL the form fields in the document
//	 */
//	@RequestMapping(value = "/parse-form", method = RequestMethod.POST, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter parseForm(
//			String s3Key
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
//	
//	/**
//	 * Merge form data with a fillable form document
//	 * 
//	 * @param s3Key The location of the original document
//	 * @formData the data that need to go into the form
//	 * 
//	 * @return A s3Key for the document with form data applied
//	 */
//	@RequestMapping(value = "/merge-form", method = RequestMethod.POST, headers = { "Accept=application/json" })
//	public @ResponseBody DefaultOutParameter mergeForm(
//			String s3Key,
//			String formData // JSON string	
//			) 
//	{
//		// TODO: add code
//		return null;
//	}
}
